package com.lsy.common.result;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.StringWriter;

@Data
@ToString
@Slf4j
@NoArgsConstructor
public class CommonResult<T>{
	private Boolean beSuccess = true;
	private Integer code = CommonResultConst.SUCCESS_CODE;
	private String msg = "";
	private T data;
	private String exception;
	
	public CommonResult(Integer code, String msg) {
		this.beSuccess = false;
		this.code = code;
		this.msg = msg;
	}
	
	public void fail(CommonResultException e){
		this.fail(e.getCode(),e.getMsg());
	}
	
	public void fail(Integer code, String msg){
		this.beSuccess = false;
		this.code = code;
		this.msg = msg;
	}
	
	public void exception(Exception e){
		if(e.getClass()== CommonResultException.class){
			this.fail((CommonResultException) e);
			return;
		}
		this.fail(CommonResultConst.EXCEPTION_CODE,e.getMessage());
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		this.exception = sw.toString();
		log.error(this.msg, this.exception);
	}
}
